package com.gemcoder.system.datasource;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.function.Predicate;


public class JdbcTemplateUtil {
    private final static String SELECT = "select";
    private final static int LENGTH_SIX = 6;

    public static <T> T executeSQL(String sql, Object... args) {
        JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);
        Predicate<String> judgeExist = StrUtil::isNotEmpty;
        Predicate<String> judgeLength = param -> param.trim().length() > LENGTH_SIX;
        Predicate<String> judgeHead = param -> param.trim().toLowerCase().startsWith(SELECT);
        Predicate<String> judgeHave = param -> param.trim().toLowerCase().contains("set");
        boolean isSelect = judgeExist.and(judgeLength).and(judgeHead).test(sql) || judgeHead.and(judgeHave).test(sql);
        if (isSelect) {
            if (args == null || args.length == 0) {
                return (T) jdbcTemplate.queryForList(sql);
            }else {
                return (T) jdbcTemplate.queryForList(sql,args);
            }
        } else {
            if (args == null || args.length == 0) {
                return (T) Integer.valueOf(jdbcTemplate.update(sql));
            }else {
                return (T) Integer.valueOf(jdbcTemplate.update(sql,args));
            }
        }
    }
}
